<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background: linear-gradient(135deg, #6e8efb, #a777e3);
            color: #333;
        }

        .login-container {
            background-color: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            width: 350px;
            text-align: center;
        }

        .login-container h2 {
            font-size: 24px;
            margin-bottom: 20px;
            color: #007bff;
        }

        .form-group {
            margin-bottom: 15px;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }

        .form-group input:focus {
            border-color: #007bff;
            outline: none;
        }

        .btn {
            width: 100%;
            padding: 12px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn:hover {
            background-color: #0056b3;
        }

        .btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .error-message {
            color: red;
            font-size: 14px;
            margin-top: 10px;
            text-align: left;
        }

        .extra-info {
            margin-top: 15px;
            font-size: 14px;
            color: #666;
        }

        .extra-info a {
            color: #007bff;
            text-decoration: none;
            font-weight: bold;
            cursor: pointer;
        }

        .extra-info a:hover {
            text-decoration: underline;
        }

        .code-group {
            display: flex;
            align-items: flex-end;
            gap: 10px;
        }

        .code-group input {
            flex: 1;
            margin-bottom: 0;
        }

        .code-group button {
            padding: 10px 20px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            height: 38px;
            line-height: 1;
        }

        .code-group button:hover {
            background-color: #218838;
        }

        .code-group button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .login-type {
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            gap: 20px;
        }

        .login-type label {
            font-weight: normal;
            color: #333;
            cursor: pointer;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 12px;
            width: 350px;
            text-align: center;
            position: relative;
        }

        .close-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 20px;
            cursor: pointer;
            color: #666;
        }

        .close-btn:hover {
            color: #333;
        }

        .captcha-group {
            display: flex;
            align-items: flex-end;
            gap: 10px;
        }

        .captcha-group input {
            flex: 1;
            margin-bottom: 0;
        }

        .captcha-group img {
            height: 38px;
            cursor: pointer;
            border-radius: 6px;
        }
    </style>
</head>
<body>
<div class="login-container">
    <h2>用户登录</h2>
    <div id="error-message" class="error-message"></div>
    <div class="login-type">
        <label><input type="radio" name="loginType" value="password" checked> 密码登录</label>
        <label><input type="radio" name="loginType" value="code"> 验证码登录</label>
    </div>
    <form id="login-form">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" placeholder="请输入用户名" required>
        </div>
        <div class="form-group" id="password-group">
            <label for="password">密码</label>
            <input type="password" id="password" placeholder="请输入密码" required>
        </div>
        <div class="form-group captcha-group" id="captcha-group">
            <div style="flex: 1;">
                <label for="captcha">验证码</label>
                <input type="text" id="captcha" placeholder="请输入验证码" required>
            </div>
            <img id="captcha-image" alt="验证码" onclick="getCaptcha()">
        </div>
        <div class="form-group" id="phone-group" style="display: none;">
            <label for="phoneNum">手机号</label>
            <input type="text" id="phoneNum" placeholder="请输入手机号">
        </div>
        <div class="form-group code-group" id="code-group" style="display: none;">
            <div style="flex: 1;">
                <label for="code">验证码</label>
                <input type="text" id="code" placeholder="请输入验证码">
            </div>
            <button type="button" id="send-code-btn">发送验证码</button>
        </div>
        <button type="submit" class="btn">登录</button>
        <div class="extra-info">
            还没有账号？<a id="register-link">立即注册</a> | <a id="update-password-link">修改密码</a>
        </div>
    </form>
</div>

<div id="register-modal" class="modal">
    <div class="modal-content">
        <span class="close-btn" id="close-modal">×</span>
        <h2>用户注册</h2>
        <div id="register-error" class="error-message"></div>
        <form id="register-form">
            <div class="form-group">
                <label for="reg-username">用户名</label>
                <input type="text" id="reg-username" placeholder="请输入用户名" required>
            </div>
            <div class="form-group">
                <label for="reg-password">密码</label>
                <input type="password" id="reg-password" placeholder="请输入密码" required>
            </div>
            <div class="form-group">
                <label for="reg-email">邮箱</label>
                <input type="email" id="reg-email" placeholder="请输入邮箱" required>
            </div>
            <div class="form-group">
                <label for="reg-phone">手机号</label>
                <input type="text" id="reg-phone" placeholder="请输入手机号" required>
            </div>
            <button type="submit" class="btn">注册</button>
        </form>
    </div>
</div>

<div id="update-password-modal" class="modal">
    <div class="modal-content">
        <span class="close-btn" id="close-update-modal">×</span>
        <h2>修改密码</h2>
        <div id="update-error" class="error-message"></div>
        <form id="update-password-form">
            <div class="form-group">
                <label for="update-username">用户名</label>
                <input type="text" id="update-username" placeholder="请输入用户名" required>
            </div>
            <div class="form-group">
                <label for="update-old-password">旧密码</label>
                <input type="password" id="update-old-password" placeholder="请输入旧密码" required>
            </div>
            <div class="form-group">
                <label for="update-password">新密码</label>
                <input type="password" id="update-password" placeholder="请输入新密码" required>
            </div>
            <div class="form-group">
                <label for="update-email">邮箱</label>
                <input type="email" id="update-email" placeholder="请输入邮箱" required>
            </div>
            <button type="submit" class="btn">提交</button>
        </form>
    </div>
</div>

<script>
    const sendCodeBtn = document.getElementById('send-code-btn');
    const loginForm = document.getElementById('login-form');
    const errorMessage = document.getElementById('error-message');
    const passwordGroup = document.getElementById('password-group');
    const phoneGroup = document.getElementById('phone-group');
    const codeGroup = document.getElementById('code-group');
    const captchaGroup = document.getElementById('captcha-group');
    const loginTypeRadios = document.querySelectorAll('input[name="loginType"]');
    const registerLink = document.getElementById('register-link');
    const registerModal = document.getElementById('register-modal');
    const closeModal = document.getElementById('close-modal');
    const registerForm = document.getElementById('register-form');
    const registerError = document.getElementById('register-error');
    const updatePasswordLink = document.getElementById('update-password-link');
    const updatePasswordModal = document.getElementById('update-password-modal');
    const closeUpdateModal = document.getElementById('close-update-modal');
    const updatePasswordForm = document.getElementById('update-password-form');
    const updateError = document.getElementById('update-error');
    let countdown = 60;
    let timer = null;

    // 获取验证码图片
    function getCaptcha() {
        fetch('/api/auth/captcha', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    document.getElementById('captcha-image').src = data.data.captchaImage;
                } else {
                    errorMessage.textContent = data.message || '获取验证码失败';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                errorMessage.textContent = '获取验证码时发生错误';
            });
    }

    // 切换登录方式
    loginTypeRadios.forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.value === 'password') {
                passwordGroup.style.display = 'block';
                captchaGroup.style.display = 'flex';
                phoneGroup.style.display = 'none';
                codeGroup.style.display = 'none';
                document.getElementById('password').required = true;
                document.getElementById('captcha').required = true;
                document.getElementById('phoneNum').required = false;
                document.getElementById('code').required = false;
            } else {
                passwordGroup.style.display = 'none';
                captchaGroup.style.display = 'none';
                phoneGroup.style.display = 'block';
                codeGroup.style.display = 'flex';
                document.getElementById('password').required = false;
                document.getElementById('captcha').required = false;
                document.getElementById('phoneNum').required = true;
                document.getElementById('code').required = true;
            }
        });
    });

    // 发送验证码
    sendCodeBtn.addEventListener('click', function() {
        const username = document.getElementById('username').value.trim();
        const phoneNum = document.getElementById('phoneNum').value.trim();

        if (!username || !phoneNum) {
            errorMessage.textContent = '请填写用户名和手机号';
            return;
        }

        sendCodeBtn.disabled = true;
        sendCodeBtn.textContent = `${countdown}s 后重试`;
        timer = setInterval(() => {
            countdown--;
            sendCodeBtn.textContent = `${countdown}s 后重试`;
            if (countdown <= 0) {
                clearInterval(timer);
                sendCodeBtn.disabled = false;
                sendCodeBtn.textContent = '发送验证码';
                countdown = 60;
            }
        }, 1000);

        fetch('/api/auth/loginPhone', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username,
                phoneNum,
                email: ''
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    errorMessage.style.color = 'green';
                    errorMessage.textContent = '验证码发送成功';
                } else {
                    errorMessage.textContent = data.message || '验证码发送失败';
                    clearInterval(timer);
                    sendCodeBtn.disabled = false;
                    sendCodeBtn.textContent = '发送验证码';
                    countdown = 60;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                errorMessage.textContent = '发送验证码时发生错误';
                clearInterval(timer);
                sendCodeBtn.disabled = false;
                sendCodeBtn.textContent = '发送验证码';
                countdown = 60;
            });
    });

    // 登录表单提交
    loginForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('username').value.trim();
        const loginType = document.querySelector('input[name="loginType"]:checked').value;

        if (loginType === 'password') {
            const password = document.getElementById('password').value.trim();
            const captcha = document.getElementById('captcha').value.trim();
            if (!username || !password || !captcha) {
                errorMessage.textContent = '请填写用户名、密码和验证码';
                return;
            }

            fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password, captcha })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        localStorage.setItem('token', data.data.token);
                        localStorage.setItem('username', data.data.username);
                        errorMessage.style.color = 'green';
                        errorMessage.textContent = data.message || '登录成功';
                        setTimeout(() => {
                            window.location.href = 'http://localhost:8080/users.html';
                        }, 1000);
                    } else {
                        errorMessage.style.color = 'red';
                        errorMessage.textContent = data.message || '登录失败，请检查输入';
                        getCaptcha(); // 刷新验证码
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    errorMessage.textContent = '登录时发生了一个错误，请稍后再试';
                    getCaptcha(); // 刷新验证码
                });
        } else {
            const phoneNum = document.getElementById('phoneNum').value.trim();
            const code = document.getElementById('code').value.trim();
            if (!username || !phoneNum || !code) {
                errorMessage.textContent = '请填写所有必填项';
                return;
            }

            fetch('/api/auth/checkCode', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    username,
                    phoneNum,
                    code,
                    email: ''
                })
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        localStorage.setItem('token', data.data.token);
                        localStorage.setItem('username', data.data.username);
                        errorMessage.style.color = 'green';
                        errorMessage.textContent = data.message || '登录成功';
                        setTimeout(() => {
                            window.location.href = 'http://localhost:8080/users.html';
                        }, 1000);
                    } else {
                        errorMessage.style.color = 'red';
                        errorMessage.textContent = data.message || '验证码错误或已过期';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    errorMessage.textContent = '登录时发生了一个错误，请稍后再试';
                });
        }
    });

    // 注册相关逻辑
    registerLink.addEventListener('click', function() {
        registerModal.style.display = 'flex';
    });

    closeModal.addEventListener('click', function() {
        registerModal.style.display = 'none';
        registerError.textContent = '';
        registerForm.reset();
    });

    registerModal.addEventListener('click', function(event) {
        if (event.target === registerModal) {
            registerModal.style.display = 'none';
            registerError.textContent = '';
            registerForm.reset();
        }
    });

    registerForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('reg-username').value.trim();
        const password = document.getElementById('reg-password').value.trim();
        const email = document.getElementById('reg-email').value.trim();
        const phone = document.getElementById('reg-phone').value.trim();

        if (!username || !password || !email || !phone) {
            registerError.textContent = '请填写所有必填项';
            return;
        }

        fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username,
                password,
                email,
                phone
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    registerError.style.color = 'green';
                    registerError.textContent = '注册成功';
                    setTimeout(() => {
                        registerModal.style.display = 'none';
                        registerForm.reset();
                        errorMessage.style.color = 'green';
                        errorMessage.textContent = '注册成功，请登录';
                    }, 1000);
                } else {
                    registerError.style.color = 'red';
                    registerError.textContent = data.message || '注册失败';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                registerError.textContent = '注册时发生了一个错误，请稍后再试';
            });
    });

    // 修改密码相关逻辑
    updatePasswordLink.addEventListener('click', function() {
        updatePasswordModal.style.display = 'flex';
    });

    closeUpdateModal.addEventListener('click', function() {
        updatePasswordModal.style.display = 'none';
        updateError.textContent = '';
        updatePasswordForm.reset();
    });

    updatePasswordModal.addEventListener('click', function(event) {
        if (event.target === updatePasswordModal) {
            updatePasswordModal.style.display = 'none';
            updateError.textContent = '';
            updatePasswordForm.reset();
        }
    });

    updatePasswordForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('update-username').value.trim();
        const oldPassword = document.getElementById('update-old-password').value.trim();
        const password = document.getElementById('update-password').value.trim();
        const email = document.getElementById('update-email').value.trim();

        if (!username || !oldPassword || !password || !email) {
            updateError.textContent = '请填写所有必填项';
            return;
        }

        fetch('/api/auth/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                username: username,
                password: password,
                email: email,
                oldPassword: oldPassword
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    updateError.style.color = 'green';
                    updateError.textContent = data.message || '修改成功';
                    setTimeout(() => {
                        updatePasswordModal.style.display = 'none';
                        updatePasswordForm.reset();
                        errorMessage.style.color = 'green';
                        errorMessage.textContent = '密码修改成功，请使用新密码登录';
                    }, 1000);
                } else {
                    updateError.style.color = 'red';
                    updateError.textContent = data.message || '修改失败，请检查输入';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                updateError.textContent = '修改密码时发生了一个错误，请稍后再试';
            });
    });

    // 初始化加载验证码
    window.onload = function() {
        getCaptcha();
    };
</script>
</body>
</html>